<?php
/**
 * @fileName:Crypt.php
 * @project: miaosang
 * @nameSpace:${NAMESPACE}
 * @Class Crypt
 * @author : 吐火青蛙
 * @user : 吐火青蛙
 * @date : 2021-08-22 10:02
 * @desc : Crypt
 * @Copyright (c)  2021,All Rights Reserved.
 */
namespace miaosang\yii2\safety;
use miaosang\yii2\bases\Component;
class Crypt extends Component
{
	/**
	 * @desc key 获取
	 * @var 加密密钥
	 */
	public $key = '1234¥@#!%';

	public function __construct($config = [])
	{
		parent::__construct($config);
	}

	/**
	 * @desc 加密函数
	 * @param $data
	 * @return string
	 */
	public function encrypt($data): string
	{
		$l = strlen($this->key);
		if ($l < 16) $this->key = str_repeat($this->key, ceil(16/$l));

		if ($m = strlen($data)%8) $data .= str_repeat("\x00",  8 - $m);
		if (function_exists('mcrypt_encrypt'))
			$val = mcrypt_encrypt(MCRYPT_BLOWFISH, $this->key, $data, MCRYPT_MODE_ECB);
		else
			$val = openssl_encrypt($data, 'BF-ECB', $this->key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING);
		return base64_encode($val );
	}

	/**
	 * @desc 解密函数
	 * @param $data
	 * @return false|string
	 */
	public function decrypt($data){
		$data = base64_decode($data);
		$l = strlen($this->key);
		if ($l < 16) $this->key = str_repeat($this->key, ceil(16/$l));

		if (function_exists('mcrypt_encrypt'))
			$val = mcrypt_decrypt(MCRYPT_BLOWFISH, $this->key, $data, MCRYPT_MODE_ECB);
		else
			$val = openssl_decrypt($data, 'BF-ECB', $this->key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING);
		return $val;
	}
}